package com.bankcomm.ui.specialwidget;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.bankcomm.R;
import com.bankcomm.bean.GroupCity;
import com.bankcomm.bean.ItemCity;
import com.bankcomm.common.LPMid;
import com.bankcomm.ui.BaseViewCopy;
import com.bankcomm.ui.adapter.CityNameAdapter;
import com.bankcomm.util.LPUtils;
import com.rytong.tools.ui.BaseView;
import com.rytong.tools.ui.Component;
import com.rytong.tools.utils.Utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.LinearLayout;
import android.widget.ListView;

/**
 * 本地生活城市选择控件
 * sun_t.sdc
 */
public class LPLocalCity extends Component {
	private CityNameAdapter adapter;
	
	/** activity */
	private BaseView bv_ = null;
	
	@Override
	public void initRealView(Activity activity, String nodeValue) {
		realView_ = new MyLPLocalCity(activity);
	}

	public class MyLPLocalCity extends LinearLayout implements CompositedComponent {
		private com.bankcomm.ui.specialwidget.SideBar indexBar;
		private ArrayList<GroupCity> list;
		private ListView mListView;
		
		public MyLPLocalCity(Context context) {
			super(context);
			bv_ = (BaseView) context;
			
			LayoutInflater.from(context).inflate(R.layout.bcm_localcity_item_layout,this);
			mListView = (ListView) this.findViewById(R.id.list_city);
			mListView.setSelector(new ColorDrawable());
			indexBar = (SideBar) findViewById(R.id.sideBar);
			list = new ArrayList<GroupCity>();
			Object data = getPropertyByName("citys");
			int col = getPropertyByName("col") != null ? Integer.valueOf(getPropertyByName("cityCol").toString()) : 3;
			// 获取数据
			if (!data.equals("")) {
				list = handlerJsonData(data);
			}
			// 实例化自定义内容适配类
			adapter = new CityNameAdapter(context,LPLocalCity.this, list, col);
			
			// 为listView设置适配
			mListView.setAdapter(adapter);
			
			indexBar.setListView(mListView);
		}
		/*
		 * 得到数据并对数据进行a-z排序
		 */
		private ArrayList<GroupCity> handlerJsonData(Object citysObj) {
			ArrayList<GroupCity> groupCities = null;
			if (citysObj != null) {
				groupCities = new ArrayList<GroupCity>();
				try {
					JSONArray citysJA = new JSONArray(citysObj.toString());
					for (int i = 0; i < citysJA.length(); i++) {
						JSONObject citysJO = (JSONObject) citysJA.get(i);

						// 若是"其他"则通过算法找出分类标识(A-G...)
						String groupText = citysJO.getString("group");
						if (groupText != null && (bv_.getString(R.string.others)).equals(groupText)) {

							List<ItemCity> itemCitys = new ArrayList<ItemCity>();
							JSONArray cityJA = new JSONArray(citysJO.getString("itemCitys"));
							for (int j = 0; j < cityJA.length(); j++) {
								JSONObject cityJO = (JSONObject) cityJA.get(j);
								String cityName = cityJO.getString("name");
								String cityShort = LPUtils.cn2pinyin(cityName); // 得到城市简拼
								ItemCity itemCity = new ItemCity(cityName, cityJO.getString("value"), cityShort.toUpperCase());
								
								String url = cityJO.getString("url");	// 得到城市对应的url
								itemCity.setUrl(url);
								
								itemCitys.add(itemCity);
							}

							// 开始排序
							if (!itemCitys.isEmpty()) {
								Collections.sort(itemCitys, new Comparator<ItemCity>() {
									@Override
									public int compare(ItemCity o1, ItemCity o2) {
										return o1.getSearchkey().toUpperCase().compareTo(o2.getSearchkey().toUpperCase());
									}
								});

								// 排序完后, 对列表加入字母
								char prevch = '0';
								GroupCity currGC = null;
								List<ItemCity> currIC = null;
								char c = 'A';
								char[] ca = new char[26];
								int a = 0;
								int size = 0;
								
								for (int j = 0; j < ca.length; j++) {
									ca[j] = (char)c++;
									char ch = 0;
									
									/* 判断第一个字母出现次数 */
									for (ItemCity itemCity : itemCitys) {
										char c1 = itemCity.getSearchkey().toUpperCase().charAt(0);
										if (c1 == ca[j]){
											size++;
										}
									}

									
									for (int m = 0; m < itemCitys.size(); m++) {
										ItemCity itemCity = itemCitys.get(m);

										ch = itemCity.getSearchkey().toUpperCase().charAt(0);
										
										if (ch == ca[j]) {
											if (prevch == '0') {
												if (a == 0) {
													currIC = new ArrayList<ItemCity>();
													currGC = new GroupCity();
													currGC.setGroupBy((new Character(
																	ca[j]))
																	.toString()
																	.toUpperCase());
												}
												currIC.add(itemCity);
												a++;
												if (size == a) {
													prevch = '1';
												}
											} else {
												if (a == 0) {
													currGC.setItemCitys(currIC);
													groupCities.add(currGC);
													currIC = new ArrayList<ItemCity>();
													currGC = new GroupCity();
													currGC.setGroupBy((new Character(
																	ca[j]))
																	.toString()
																	.toUpperCase());
												}
												currIC.add(itemCity);
												a++;
											}
										}
									}
									a = 0;
								}
								currGC.setItemCitys(currIC);
								groupCities.add(currGC);
							}
						} 
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return groupCities;
		}
		
		@Override
		public Component composited() {
			return LPLocalCity.this;
		}
		
		@Override
		public boolean onInterceptTouchEvent(MotionEvent ev) {
			ViewGroup vf = (ViewGroup) getParent();
			ViewGroup vg = (ViewGroup) vf.getParent();
			if (vg == null) {
				return super.onInterceptTouchEvent(ev);
			} else {
				if (ev.getAction() == MotionEvent.ACTION_DOWN) {
					// 将父scrollview的滚动事件拦截
					vg.requestDisallowInterceptTouchEvent(true);
				} else if (ev.getAction() == MotionEvent.ACTION_UP) {
					// 把滚动事件恢复给父Scrollview
					vg.requestDisallowInterceptTouchEvent(false);
				}
			}
			return super.onInterceptTouchEvent(ev);
		}
	}
	
	
	/**
	 * 发起请求
	 */
	public void sendRequest(ItemCity item){
		String name = getPropertyByName("name");
		String cityValue = item.getValue();
		String url = item.getUrl();
		if (null != name && url != null && !"".equals(url) ) {
			try {
				url = url + "&"+name+"="+cityValue;
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(null != getActivity()){
				LPMid.getInstance().um_.dealWithLink(url, (BaseViewCopy)getActivity());				
			}
		}
	}
	
	@Override
	public void mouldH() throws Exception {
		super.mouldH();
		//高度 
		AbsoluteLayout.LayoutParams lp = (android.widget.AbsoluteLayout.LayoutParams) getLayoutParams();
		if(null != lp){
			lp.height = Utils.getScaledValueY(280);
			this.setLayoutParams(lp);			
		}
	}
}